package com.tfd.blog.controller;

import com.tfd.blog.filter.NeedLogin;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author TangFD
 * @since 2019/5/7.
 */
@Slf4j
@RestController
public class FileController {

    @Value("${blog.file.path}")
    private String basePath;

    @NeedLogin
    @RequestMapping("/upload")
    public Map<String, Object> upload(MultipartFile file) {
        Map<String, Object> result = new HashMap<>(3);
        if (file.isEmpty()) {
            result.put("success", false);
            return result;
        }


        String filename = file.getOriginalFilename();
        String fileId = UUID.randomUUID().toString().replace("-", "");
        filename = fileId + filename.substring(filename.lastIndexOf("."), filename.length());
        String filePath = basePath + fileId;
        File dest = new File(filePath);
        try {
            if (!dest.exists()) {
                dest.createNewFile();
            }

            file.transferTo(dest);
            result.put("success", true);
            result.put("fid", fileId);
            result.put("url", "web-static/" + fileId);
            return result;
        } catch (IOException e) {
            log.error(e.toString(), e);
            result.put("success", false);
        }

        return result;
    }

}
